home *** CD-ROM | disk | FTP | other *** search
- Path: gail.ripco.com!mambuhl
- From: mambuhl@ripco.com (Martin Ambuhl)
- Newsgroups: comp.lang.c
- Subject: Unable to check calloc`s
- Date: 4 Feb 1996 16:01:14 GMT
- Organization: Ripco Communications, Inc.
- Message-ID: <4f2l8a$c98@gail.ripco.com>
- NNTP-Posting-Host: golden.ripco.com
-
- s910500@acs.csc.cuhk.hk (CHAN CHUN CHUNG)
- in <4emept$ifv@hpg30a.csc.cuhk.hk> asks:
-
- >Could anyone tell me why the following line is complained by the
- >compiler?
-
- >if ((float **x = (float **) calloc(9, sizeof(float *)))
- > == 0) exit(1);
-
- >What's the right way to check the calloc's return value?
-
- Let's clean this up (not all changes are for errors) one step at a time.
-
- 1) Declarations go at the top of a block. Let's make a block for context:
- {
- float **x;
- if (x = (float **) calloc(9, sizeof(float *))) == 0) exit(1);
- }
-
- 2) exit(1) is not portable. If you want to return a failure code,
- the portable way is:
- #include <stdlib.h>
- {
- float **x;
- if (x = (float **) calloc(9, sizeof(float *))) == 0)
- exit(EXIT_FAILURE);
- }
-
- 3) casting the return from ?alloc may mask the failure to #include
- <stdlib.h>. If you know enough about the proper cast to specify it,
- then you don't need it:
- #include <stdlib.h>
- {
- float **x;
- if (x = calloc(9, sizeof(float *))) == 0)
- exit(EXIT_FAILURE);
- }
-
- 4) calloc zeros out memory. This does not mean that pointers are set to
- NULL or that floating values are set to a value of floating point
- zero. It is also true that this is frequently wasted effort even
- for integral values. malloc() is usually what you want:
- #include <stdlib.h>
- {
- float **x;
- if (x = malloc(9*sizeof(float *))) == 0)
- exit(EXIT_FAILURE);
- }
-
- 5) Hard coding constant values is usually a mistake:
- #include <stdlib.h>
- #define ARRAYSIZE 9
- {
- float **x;
- if (x = malloc(ARRAYSIZE*sizeof(float *))) == 0)
- exit(EXIT_FAILURE);
- }
-
- --
- * Martin Ambuhl net: mambuhl@ripco.com
- * Chicago, IL (USA)
-